import { Spin } from "antd";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Navigate } from "react-router-dom";
import { checkLogin as _checkLogin } from "../utils/redux/slices/authSlice";

/**
 * 高阶组件：用于包裹需要登录验证的组件
 * @param {React.ComponentType} WrappedComponent - 需要被包裹的组件
 * @returns {React.Component} 包裹后的权限控制组件
 */
const withAuth = (WrappedComponent) => {
  const EnhancedComponent = (props) => {
    const [isChecking, setIsChecking] = useState(true);
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    const dispatch = useDispatch();
    const { loading } = useSelector((state) => state.store);

    // 登录检查逻辑
    useEffect(() => {
      const verifyLogin = async () => {
        try {
          const loginResult = await dispatch(_checkLogin());
          setIsLoggedIn(!!loginResult); // 根据实际返回结构调整
        } catch (error) {
          setIsLoggedIn(false);
        } finally {
          setIsChecking(false);
        }
      };
      verifyLogin();
    }, [dispatch]);

    // 检查状态中：显示加载动画
    if (isChecking) {
      return <Spin fullscreen tip="加载中..." spinning={loading} />;
    }

    // 未登录：跳转至登录页
    if (!isLoggedIn) {
      return <Spin fullscreen tip="加载中..." spinning={loading} />;
    }

    // 已登录：渲染目标组件 + 全局加载动画
    return (
      <>
        <Spin fullscreen spinning={loading} tip="加载中..." />
        <WrappedComponent {...props} />
      </>
    );
  };

  // 给组件添加displayName便于调试
  const name = WrappedComponent.displayName || WrappedComponent.name;
  EnhancedComponent.displayName = `withAuth(${name})`;

  return EnhancedComponent;
};

export default withAuth;
